import 'package:enterprise_v6_app/app/components/toast_widget.dart';
import 'package:enterprise_v6_app/app/core/core.dart';
import 'package:enterprise_v6_app/app/core/http/http.dart';
import 'package:enterprise_v6_app/app/core/utils/interface.dart';
import 'package:enterprise_v6_app/app/data/entities/application/emergency/exercise_plan_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/role_personnel_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/application/special_list/process_nodes_entity.dart';
import 'package:enterprise_v6_app/app/data/entities/task/process_currency_emergency_entity.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_emergency/common/approval_people_widget.dart';
import 'package:enterprise_v6_app/app/modules/task/task_all/task_emergency/task_drill_plan/task_drill_plan_controller.dart';

class DrillPlanApprovalController extends GetxController with GetSingleTickerProviderStateMixin {
  /// 外部列表controller
  final taskController = Get.find<TaskDrillPlanController>();

  /// 预案id
  String id = Get.arguments as String;

  /// TabController 变量
  late TabController tabController;

  /// 审批流程数据
  List<ProcessNodesEntity>? nodeList;

  /// 数据实体
  ExercisePlanEntity entity = ExercisePlanEntity();

  /// 流程执行实体
  ProcessCurrencyEmergencyEntity executeEntity = ProcessCurrencyEmergencyEntity();

  /// 下一个节点的执行人 有则修改，空则不管
  List<RolePersonnelEntity> nextNodeExecutor = [];

  @override
  void onInit() {
    super.onInit();
    // 初始化tabController
    tabController = TabController(vsync: this, length: 4);
    // 获取基本信息详情
    getDetailsData();
    // 获取演练流程数据详情
    getProcessListData();
  }

  /// 获取详情数据
  void getDetailsData() async {
    // 获取基本信息接口
    final res = await HttpUtil().generateGetRequest<ExercisePlanEntity>(
      Interface.getExercisePlan,
      queryParameters: {'id': id},
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        entity = result.data!;
      }
      update();
    });
  }

  /// 获取流程列表数据
  void getProcessListData() async {
    // 获取流程列表接口
    final res = await HttpUtil().generateGetRequest<List<ProcessNodesEntity>>(
      Interface.getProcessArrangeRecord,
      queryParameters: {'emergencyPlansId': id, 'businessType': 'm1'},
    ).execute();
    res.onSuccess((result) {
      if (result.data != null) {
        nodeList = result.data!;
      }
      update();
    });
  }

  /// 输入回调
  void onOpinion(String value) {
    executeEntity.approvalOpinions = value;
    update();
  }

  /// 签字回调
  void onSign(String url) {
    executeEntity.approvalUser = url;
  }

  /// 操作回调
  /// [type]1:通过 2:不通过
  Future<void> onOperation(int type) async {
    // 当前执行节点
    final implementNode = taskController.implementNode;
    // 是否为结束节点的前一个节点
    final last = taskController.last;
    executeEntity.id = id;
    executeEntity.last = last;
    executeEntity.nodeId = implementNode.nodeId!;
    executeEntity.rtNodeId = implementNode.id!;
    executeEntity.processEncoding = implementNode.processEncoding!;
    executeEntity.rtemplateId = implementNode.rtemplateId!;
    executeEntity.status = type;
    // 不为最后一个节点,设置下个执行人
    if (!last && type == 1) {
      nextNodeExecutor.clear();
      nextNodeExecutor.addAll(taskController.nextNode.rtUserProcesses!);
      //弹出选择负责人弹窗
      Get.dialog<bool>(
        ApprovalPeopleWidget(
          nextNodeExecutor: nextNodeExecutor,
          callback: () async {
            Get.back();
            executeEntity.nextNodeExecutor = nextNodeExecutor;
            emergencyExecute(type);
          },
        ),
      );
    } else {
      emergencyExecute(type);
    }
  }

  /// 执行流程
  Future<void> emergencyExecute(int type) async {
    // 执行审批流程
    // 调用流程节点执行接口
    final res = await HttpUtil().generatePostRequest(Interface.exercisePlanExecute, data: executeEntity.toJson()).execute(isShowLoading: true);
    res.onSuccess((result) {
      taskController.refreshPage();
      Get.back();
      AppToast.showWarning(type == 1 ? '通过成功!' : '驳回成功!');
    });
    res.onError((result) {
      AppToast.showWarning(type == 1 ? '通过失败!' : '驳回失败!');
    });
  }
}
